<template>
  <div class="app-container">

    <!--总揽：
    1-搜索框
    2-表格
    3-分页插件条
    4-隐藏页面-“新增”/“编辑” 弹窗
    5-隐藏页面-“删除” 弹窗
    -->

    <!--  1-搜索框    -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">

        <!--条件框1、根据状态筛选-->
        <el-form-item>
          <el-select v-model="value" clearable placeholder="状态">
            <el-option
              v-for="item in status"
              :key="item.statusId"
              :label="item.label"
              :value="item.statusId">
            </el-option>
          </el-select>
        </el-form-item>

        <!--条件框2、根据命名筛选-->
        <el-form-item>
          <el-input   placeholder="名称" v-model="searchName"></el-input>
        </el-form-item>

        <!--“搜索”按钮-->
        <el-form-item>
          <el-button type="primary" @click="doFilter()"><i class="el-icon-search"></i>搜索</el-button>
        </el-form-item>

        <!--“新增”按钮-->
        <el-form-item>
          <el-button type="primary" @click="addUpdate()">新增</el-button>
        </el-form-item>

      </el-form>
    </el-col>


    <div>

      <div style="float:left; width: 50%;">
        <viewer span="6" style="width: 100%;height: 100%">

          <img :src="this.formData.testImgUrl" style="max-width: 90%; max-height: 100%; width: 2000px">

        </viewer>
      </div>

      <el-upload
        class="upload-demo"
        action="http://10.103.241.48:9526/species/updateSpeciesPic1"
        :data="curSpecies"
        name="file"
        :on-success="handlePic1UploadSuccess"
      >
        <el-button size="small" type="primary">点击上传图片-1</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>

      <div style="float:right; width: 50%;">


        <!-- 2-列表     -->


        <el-table :data="tableList"  :height="tableHeight" max-height="450" v-loading="listLoading"   border element-loading-text="拼命加载中" style="width: 100%;">
          <!--1）第一列，-->
          <el-table-column prop="id" label="大田序号"> </el-table-column>
          <!--2) 第二列-->
          <el-table-column prop="name" label="大田名称"> </el-table-column>
          <el-table-column prop="length" label="长度"> </el-table-column>
          <el-table-column prop="width" label="宽度"> </el-table-column>
          <el-table-column prop="year" label="年份"> </el-table-column>


          <!-- 3） 第三列 自定义列；"operation"为列表中没有的字段；    -->
          <el-table-column prop="operation" label="操作 ">
            <!--把遍历列表中取出的每一项命名为“scope”；它包含“row”、“$index”两个字段，“row”中就是列表中的一项，“$index”应该是框架自动给加的编号-->
            <template slot-scope="scope">

              <!--操作1、编辑项目，显示编辑条目弹窗-->
              <!--<el-button size="small" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>-->
              <el-button size="small" type="primary" @click="editBigfarm(scope.row)">规划</el-button>

              <!--操作2、 进入跳转到bigfarm的详情，即farmlist页面-->
              <el-button  size="mini" type="success" @click="getInFarmList(scope.row)">进入</el-button>

              <!--操作3、  删除项目，显示删除弹窗-->
              <el-button size="small" type="danger" @click="deleteUpdate(scope.row)">删除</el-button>

            </template>
          </el-table-column>

        </el-table>

        <!--  3-分页插件的工具条                 -->
        <el-pagination layout="total, prev, pager, next"
                       background
                       :page-size="10"
                       @size-change="handleSizeChange"
                       :total="total"
                       @current-change="handleCurrentChange"
                       style="text-align:center;">
        </el-pagination>


      </div>
    </div>

    <!-- 4-隐藏页面-编辑field信息弹窗                      -->
    <el-dialog title="Edit" :visible.sync="isShowEditVisible">

      <el-form label-width="80px" :model="farmlandMsg" ref="dataForm">
        <el-form-item label="Field名称" prop="fieldName">
          <el-input v-model="farmlandMsg.name"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="farmlandMsg.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowEditVisible = false">取消</el-button>
        <el-button type="primary" :loading="listLoading" @click="updateData( farmlandMsg)" class="title1">确定</el-button>
      </div>

    </el-dialog>

    <!-- 5-新增bigfarm弹窗详情 -->
    <el-dialog title="新增" :visible.sync="isShowAddVisible">
      <el-form label-width="80px" :model="bigfarmMsg" ref="dataForm">
        <el-form-item label="名字" prop="name">
          <el-input v-model="bigfarmMsg.name"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="bigfarmMsg" ref="dataForm">
        <el-form-item label="年份" prop="year">
          <el-input v-model="bigfarmMsg.year"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="bigfarmMsg" ref="dataForm">
        <el-form-item label="长度" prop="length">
          <el-input v-model="bigfarmMsg.length"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="bigfarmMsg" ref="dataForm">
        <el-form-item label="宽度" prop="width">
          <el-input v-model="bigfarmMsg.width"></el-input>
        </el-form-item>
      </el-form>

      <el-form label-width="80px" :model="bigfarmMsg" ref="dataForm">
        <el-form-item label="描述" prop="description">
          <el-input v-model="bigfarmMsg.description"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddVisible = false">取消</el-button>
        <el-button type="primary" :loading="listLoading" @click="submitAdd(bigfarmMsg)" class="title1">确定</el-button>
      </div>

    </el-dialog>

    <!-- 6-隐藏页面-删除弹框                           -->
    <el-dialog title="删除" :visible.sync="deleteVisible" width="30%">
      <span>确认删除吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDelete">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>


<script>
  // 把getFieldList接口导入进来；
  import { getFieldList,editField,addField,deleteField } from '@/api/FarmlandManage'
  import { getAllBigfarm,getBigfarmByName,getBigfarm,addBigfarm,deleteBigfarm } from '../../api/BigFarmManage'

  /* 内含主要3部分：
  * 1、页面属性，位于data()中；
  * 2、页面初始化方法，位于created()中；
  * 3、页面方法，位于methods()中；
  *  */
  export default {

    // 一、表示属于该页面的成员属性，
    data() {

      return {

        listLoading: true,   // 等待数据加载时的动画；

        tableList: [],    // 列表中的数据；
        tableHeight: window.innerHeight * 0.6,
        total: 0,
        page: 1,
        pageSize: 10,
        filterTableDataEnd: [] , // 这个demo项目中，前端也会对后端取到的list数据进行筛选，这里存放前端筛选后的数据；

        status: [       // 筛选条件下拉框列表项：1-启用，2-禁用；
          {
            statusId: 1,
            label: '启用'
          }, {
            statusId: 0,
            label: '禁用'
          }
        ],

        value: '', // 筛选条件： 启用/禁用
        searchName: '', // 筛选条件： 名称

        isShowEditVisible: false, // “编辑field”弹窗
        deleteVisible: false, // “删除field”弹窗
        isShowAddVisible: false, // "添加field"弹窗按钮



        farmlandMsg: {
          name: '',
          remark: '',
          experimentName: '',
          shotId: '',
          rowAmount: '',
          columnAmount: '',
        },

        bigfarmMsg: {
          id: '',
          name: '',
          length: '',
          width: '',
          year: '',
          description: ''
        },

        screenWidth: document.body.clientWidth,
        bigfarmId: '',
        formData: {
          // bigfarmImgUrl: require('@/assets/images/bigfarmShot.jpg'),

          testImgUrl: require('@/assets/images/bigfarmShot.jpg'),
          motto: 'xxxxx'
        }
      }
    },


    mounted() {
      // 1、数据首次加载完后 → 获取图片（或外层框）宽度，并设置其高度
      this.$nextTick(() => {
        // 获取图片（或外层框）
        let imgBox = this.$refs.imgBox
        // 获取其宽度
        let wImgbox = imgBox[0].getBoundingClientRect().width
        // 设置其高度（以宽度的60%为例）
        this.imgBox.height = 0.6 * wImgbox + 'px'
      })
      // 2、挂载 reisze 事件 → 屏幕缩放时监听宽度变化
      const that = this
      window.onresize = () => {
        return (() => {
          window.screenWidth = document.body.clientWidth
          that.screenWidth = window.screenWidth
          console.log(that.screenWidth)
          this.$nextTick(() => {
            let imgBox = this.$refs.imgBox
            let wImgbox = imgBox[0].getBoundingClientRect().width
            this.imgBox.height = 0.6 * wImgbox + 'px'
          })
        })()
      }
    },

    watch: {
      screenWidth(val) {

        if (!this.timer) {
          this.screenWidth = val
          this.timer = true
          let that = this
          setTimeout(function() {
            console.log("自适应" + that.screenWidth)
            that.timer = false
          }, 400)
        }
      }
    },


    //二、类似于构造方法；
    created() {

      //刚打开页面时就去取数据；
      this.fetchData()

    },

    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'danger'
        }
        return statusMap[status]
      }
    },

    //三、页面中的成员方法
    methods: {

      addUpdate() {
        this.isShowAddVisible = true
      },
      //查看field内所含的plot信息，即进入plotList页面；
      getInFarmList(row) {
        this.GLOBAL.bigfarmId = row.id  //在全局变量中记录当前欲进入的bigfarm，方便field信息页面知道该加载哪个bigfarm的初始化信息；

        getBigfarm(row.id).then(response => {
          this.GLOBAL.bigfarmImgUrl = 'http://cxk.nicesite.vip/' + response.data.data.img
        })

        this.$router.push('/farm')  //路由跳转到field页面；
      },

      fetchData() {
        this.listLoading = true
        getAllBigfarm().then(response => {
          const limit = 10
          //  在前端做的一个分页查询，显示部分数据；
          const pageList = response.data.rows.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          this.total = response.data.total
          this.tableList = pageList

          console.log("屏幕高度：" + this.winHeight)
          this.listLoading = false
        })
      },
      submitAdd(bigfarmMsg) {
        addBigfarm({ 'name': this.bigfarmMsg.name, 'year': this.bigfarmMsg.year, 'description': this.bigfarmMsg.description,
                     'length': this.bigfarmMsg.length,'width': this.bigfarmMsg.width}).then(response => {
          if (response.data.success === true) {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 5000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.data.msg,
              type: 'failure',
              duration: 5000
            })
          }
          this.fetchData()
        })
        this.isShowAddVisible = false
      },
      // 用来
      doFilter() {
        if (this.searchName === '') {
          this.fetchData()
          this.$message.warning('查询条件不能为空！')
          return
        }
        this.listLoading = true
        getBigfarmByName( this.searchName ).then(response => {
          const limit = 10
          // 居然在前端做筛选，牛逼！
          const pageList = response.data.rows.filter((item, index) => index < limit * this.page && index >= limit * (this.page - 1))
          // console.log(pageList)
          this.total = response.data.total
          this.tableList = pageList
          this.listLoading = false
        })
      },

      clickfun(e) {
        console.log(e.target.innerText)
      },

      // handleUpdate(row) {
      //   this.isShowEditVisible = true
      //   this.temp = Object.assign({}, row)
      //   console.log(row)
      //   this.fieldId = row.fieldId
      // },

      editBigfarm(row) {

        console.log("正在规划的大田ID---" + row.id)
        console.log("正在规划的大田长度---" + row.length + ' 宽度  ' + row.width)

        window.open('src/editor/Farmland.html?bigFarmId=' + row.id)
      },

      deleteUpdate(row) {
        console.log(row)
        this.deleteVisible = true
        this.temp = Object.assign({}, row)
        this.bigfarmId = row.id
        // console.log(row)
      },

      submitDelete() {
        deleteBigfarm( this.bigfarmId ).then(response => {
          if (response.data.success === true) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 5000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.data.msg,
              type: 'failure',
              duration: 5000
            })
          }
          this.fetchData()
        })
        this.deleteVisible = false
      },

      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        console.log(row)
        row.status = status
      },

      updateData( farmlandMsg ) {
        // const tempData = Object.assign({}, this.temp)
        // console.log(tempData)
        // updateArticle(tempData).then(() => {
        //   for (const v of this.tableList) {
        //     if (v.uid === this.temp.uid) {
        //       const index = this.tableList.indexOf(v)
        //       this.tableList.splice(fieldList, 1, this.temp)
        //       break
        //     }
        //   }
        //   this.isShowEditVisible = false
        //   this.$notify({
        //     title: '成功',
        //     message: '更新成功',
        //     type: 'success',
        //     duration: 2000
        //   })
        // })

        editField({'fieldId': this.fieldId, 'name': farmlandMsg.name,'remark': farmlandMsg.remark}).then(response => {
          this.fetchData()
        })
        this.isShowEditVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
      },

      handleSizeChange(val) {
        this.page = val
        console.log(this.page)
        this.fetchData()
      },

      handleCurrentChange(val) {
        this.page = val
        console.log(this.page)
        this.fetchData()
      },

      currentChangePage(list) {
        let from = (this.page - 1) * this.pageSize
        const to = this.page * this.pageSize
        this.tableList = []
        for (; from < to; from++) {
          if (list[from]) {
            this.tableList.push(list[from])
          }
        }
      }

    }
  }

</script>
